package org.sloth.core
{
	public class StringUtil
	{
		/**
		 * 去掉字符串的首尾空白字符（包括空格、制表符等）
		 */		
		public static function strim(value:String):String
		{
			return value.replace(/^([\s]+)/, "").replace(/([\s]+)$/, "");
		}
		
		/**
		 * 获取字符串的长度（单字节字符为1，多字节字符为2 ）
		 */		
		public static function getLength(value:String):int
		{
			var len:int = value.length;
			for (var index:int = value.length - 1;index >= 0;index--)
			{
				if (value.charCodeAt(index) > 0xFF) len++;
			}
			return len;
		}
		
		/**
		 * 将指定字符串 <code>value</code> 按照 <code>separator</code> 分隔为多个字符串的集合，同时去掉集合中所有字符串的首尾空白字符，以及集合中的空字符串（""）
		 * @param value 
		 * @param separator
		 * @return 
		 * 
		 */		
		public static function splitAndStrim(value:String, separator:*):Array
		{
			var segSet:Array = strim(value).split(separator);
			var seg:String;
			var result:Array = [];
			for (var index:int = segSet.length - 1;index >= 0;index--)
			{
				seg = strim(String(segSet[index]));
				if (seg != "") result.push(seg);
			}
			return result;
		}
		
		/**
		 * 将指定的正整数转换成指定位数的字符串，用0填补高位。如果指定的位数小于value值的位数，则不做任何处理
		 * @param value 指定的正整数
		 * @param digit 需要的字符串位数
		 * @return 
		 * 
		 */		
		public static function fomatInt(value:uint, digit:uint):String
		{
			digit -= value.toString().length;
			var prefix:String = "";
			while (digit-- > 0)
			{
				prefix += "0"
			}
			return prefix + value.toString();
		}
		
		private static const ALPHA_CHAR_CODES:Array = [48, 49, 50, 51, 52, 53, 54, 
			55, 56, 57, 65, 66, 67, 68, 69, 70];
		/**
		 * 生成唯一标识字符串
		 */		
		public static function createUID():String
		{
			var uid:Array = new Array(36);
			var index:int = 0;
			
			var i:int;
			var j:int;
			
			for (i = 0; i < 8; i++)
			{
				uid[index++] = ALPHA_CHAR_CODES[Math.floor(Math.random() *  16)];
			}
			
			for (i = 0; i < 3; i++)
			{
				uid[index++] = 45; // charCode for "-"
				
				for (j = 0; j < 4; j++)
				{
					uid[index++] = ALPHA_CHAR_CODES[Math.floor(Math.random() *  16)];
				}
			}
			
			uid[index++] = 45; // charCode for "-"
			
			var time:Number = new Date().getTime();
			// Note: time is the number of milliseconds since 1970,
			// which is currently more than one trillion.
			// We use the low 8 hex digits of this number in the UID.
			// Just in case the system clock has been reset to
			// Jan 1-4, 1970 (in which case this number could have only
			// 1-7 hex digits), we pad on the left with 7 zeros
			// before taking the low digits.
			var timeString:String = ("0000000" + time.toString(16).toUpperCase()).substr(-8);
			
			for (i = 0; i < 8; i++)
			{
				uid[index++] = timeString.charCodeAt(i);
			}
			
			for (i = 0; i < 4; i++)
			{
				uid[index++] = ALPHA_CHAR_CODES[Math.floor(Math.random() *  16)];
			}
			
			return String.fromCharCode.apply(null, uid);
		}
	}
}